using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;

using Affirma.ThreeSharp.Model;
using Affirma.ThreeSharp.Query;
using Affirma.ThreeSharp;

namespace Affirma.CloudFront.AdminTool
{
    public partial class frmEditACL : Form
    {
        private string bucket;
        private string keyname;

        public frmEditACL(string bucket, string keyname)
        {
            InitializeComponent();
            this.bucket = bucket;
            this.keyname = keyname;
        }

        private void frmEditACL_Load(object sender, EventArgs e)
        {
            this.lblBucket.Text = this.bucket;
            this.lblKeyName.Text = this.keyname;

            using (ACLGetRequest request = new ACLGetRequest(this.bucket, this.keyname))
            {
                using (ACLGetResponse response = AccountManager.Instance.Service.ACLGet(request))
                {
                    XmlDocument acl = response.StreamResponseToXmlDocument();
                    bool isPublic = false;

                    XmlNodeList grants = acl.SelectNodes("//*[local-name()='Grant']");
                    foreach (XmlNode grant in grants)
                    {
                        string grantString = grant.InnerXml;
                        if (grantString.Contains("http://acs.amazonaws.com/groups/global/AllUsers") && grantString.Contains("READ"))
                        {
                            isPublic = true;
                        }
                    }

                    if (isPublic)
                    {
                        this.cbPublicRead.SelectedIndex = 1;
                    }
                    else
                    {
                        this.cbPublicRead.SelectedIndex = 0;
                    }
                }
            }


        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                string xAmzAcl;
                if (this.cbPublicRead.SelectedIndex == 0)
                {
                    xAmzAcl = "private";
                }
                else
                {
                    xAmzAcl = "public-read";
                }

                using (ACLChangeRequest request = new ACLChangeRequest(this.bucket, this.keyname, xAmzAcl))
                {
                    using (ACLChangeResponse response = AccountManager.Instance.Service.ACLChange(request))
                    { }
                }

                this.DialogResult = DialogResult.OK;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

    }
}